package cn.barudisshu.orm.provider.jndi;

import cn.barudisshu.orm.dialect.Dialect;
import cn.barudisshu.orm.dialect.DialectFactory;
import cn.barudisshu.orm.exception.DBException;
import cn.barudisshu.orm.provider.DataSourceProvider;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * @author Barudisshu
 */
public class JndiDataSourceProvider implements DataSourceProvider {

    private DataSource dataSource;
    private Dialect dialect;
    private String dataSourceName;
    private boolean showSql;

    public JndiDataSourceProvider(String jndiName) {
        this(jndiName, false);
    }

    public JndiDataSourceProvider(String jndiName, boolean showSql) {
        this("default", jndiName, showSql);
    }

    public JndiDataSourceProvider(String dataSourceName, String jndiName) {
        this(dataSourceName, jndiName, false);
    }

    public JndiDataSourceProvider(String dataSourceName, String jndiName, boolean showSql) {
        this(dataSourceName, jndiName, null, showSql);
    }

    public JndiDataSourceProvider(String dataSourceName, String jndiName, String dialect) {
        this(dataSourceName, jndiName, dialect, false);
    }

    public JndiDataSourceProvider(String dataSourceName, String jndiName, String dialect, boolean showSql) {
        this.dataSourceName = dataSourceName;
        Context ctx;
        try {
            ctx = new InitialContext();
            dataSource = (DataSource) ctx.lookup(jndiName);
            if (dataSource == null) {
                throw new DBException("Jndi could not found error for " + jndiName);
            }
        } catch (NamingException e) {
            throw new DBException(e.getMessage(), e);
        }
        this.dialect = DialectFactory.get(dialect == null ? "mysql" : dialect);
        this.showSql = showSql;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public Dialect getDialect() {
        return dialect;
    }

    public String getDataSourceName() {
        return dataSourceName;
    }

    public boolean isShowSql() {
        return showSql;
    }

    public JndiDataSourceProvider setShowSql(boolean showSql) {
        this.showSql = showSql;
        return this;
    }

    public void close() {
        //do nothing  becouse  it have no close method
    }
}
